package com.example.starter.security.handler;

import com.example.starter.constant.Constants;
import com.example.starter.security.constant.SecurityExceptionEnum;
import com.example.starter.util.JSONUtil;
import com.example.starter.util.ResponseEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 王令
 * @since 2022/9/18 22:24
 */
@RequiredArgsConstructor
public class ExampleAuthenticationEntryPoint extends OAuth2AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        if (authException instanceof InsufficientAuthenticationException) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType(Constants.APPLICATION_JSON_VALUE_UTF_8);
            response.getWriter().write(JSONUtil.toJsonStr(ResponseEntity.error(SecurityExceptionEnum.INVALID_TOKEN)));
        } else {
            super.commence(request, response, authException);
        }
    }
}
